﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QuickGraph;
using GxcToCsharpParser.TreeWalkers.ControlFlowGraphBuilder;
namespace GxcToCsharpParser.Utility
{
   public class QuickGraphCfgDotEngine
   {


      public void Render(AdjacencyGraph<ControlFlowGraphNode, TaggedEdge<ControlFlowGraphNode, int>> cfg, string dotFilePath)
      {
         var graphviz = new QuickGraph.Graphviz.GraphvizAlgorithm<ControlFlowGraphNode, TaggedEdge<ControlFlowGraphNode, int>>(cfg);
         graphviz.FormatEdge += new QuickGraph.Graphviz.FormatEdgeAction<ControlFlowGraphNode, TaggedEdge<ControlFlowGraphNode, int>>(graphviz_FormatEdge);
         graphviz.FormatVertex += new QuickGraph.Graphviz.FormatVertexEventHandler<ControlFlowGraphNode>(graphviz_FormatVertex);
         // render
         string output = graphviz.Generate(new QuickGraphDotEngine(), dotFilePath);

      }

      void graphviz_FormatEdge(object sender, QuickGraph.Graphviz.FormatEdgeEventArgs<ControlFlowGraphNode, TaggedEdge<ControlFlowGraphNode, int>> e)
      {

         // e.EdgeFormatter.Label.Value = (e.Edge.Tag == 1).ToString();

         switch (e.Edge.Tag)
         {
            case 0:
               e.EdgeFormatter.StrokeColor = System.Drawing.Color.Red;
               break;
            default:
               e.EdgeFormatter.StrokeColor = System.Drawing.Color.Green;
               break;

         }
      }

      void graphviz_FormatVertex(object sender, QuickGraph.Graphviz.FormatVertexEventArgs<ControlFlowGraphNode> e)
      {
         e.VertexFormatter.Label = e.Vertex.ToString();
         switch (e.Vertex.Type)
         {
            case ControlFlowNodeType.If:case ControlFlowNodeType.Switch:
               e.VertexFormatter.Shape = QuickGraph.Graphviz.Dot.GraphvizVertexShape.Diamond;
               break;
            case ControlFlowNodeType.Start:
               e.VertexFormatter.Shape = QuickGraph.Graphviz.Dot.GraphvizVertexShape.Rectangle;
               e.VertexFormatter.Style = QuickGraph.Graphviz.Dot.GraphvizVertexStyle.Rounded;
               break;
            case ControlFlowNodeType.End:
               e.VertexFormatter.Shape = QuickGraph.Graphviz.Dot.GraphvizVertexShape.Rectangle;
               e.VertexFormatter.Style = QuickGraph.Graphviz.Dot.GraphvizVertexStyle.Rounded;
               break;
            default:
               e.VertexFormatter.Shape = QuickGraph.Graphviz.Dot.GraphvizVertexShape.Rectangle;
               break;
         }

      }
    
   }
}
